package com.share.admin.config.security.bean;

import com.alibaba.fastjson.JSON;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * 在SpringSecurity中，认证或授权出现异常会被ExceptionTranslationFilter捕获到，他会去判断是认证失败还是授权失败出现异常。
 * 如果是认证过程中出现异常，那么异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint的方法对异常进行处理。
 * 如果是授权过程中出现异常，会被封装成AccessDeniedException然后调用AccessDeniedHandler的方法对异常进行处理。
 */

@Slf4j
@Component("authenticationEntryPoint")
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        log.error("认证异常-登录失败", e);
        ErrMsgEnum errMsg = ErrMsgEnum.LOGIN_ERR;
        PrintWriter writer = response.getWriter();
        if (e instanceof BadCredentialsException) {
            errMsg = ErrMsgEnum.USER_OR_PW_ERR;
        }
        writer.write(JSON.toJSONString(Result.failure(errMsg)));
        writer.flush();
        writer.close();
    }
}
